package com.bskms.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.bskms.bean.Course;
import com.bskms.bean.CourseNotification;
import com.bskms.bean.User;
import com.bskms.mapper.CourseNotificationMapper;
import com.bskms.service.CourseNotificationService;
import com.bskms.service.ClassService;
import com.bskms.service.CourseService;
import com.bskms.service.EmailService;
import com.bskms.service.UserService;

@Service
public class CourseNotificationServiceImpl implements CourseNotificationService {
    
    private static final Logger logger = LoggerFactory.getLogger(CourseNotificationServiceImpl.class);
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private EmailService emailService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CourseNotificationMapper courseNotificationMapper;
    
    @Autowired
    private ClassService classService;

    @Override
    public boolean sendAutoCourseReminder(Course course) {
        // 检查今天是否已经发送过
        if (hasSentToday(course.getId())) {
            logger.info("课程 {} 今天已经发送过提醒，跳过", course.getName());
            return true;
        }
        
        return sendCourseReminder(course, 1);
    }

    @Override
    public boolean sendManualCourseReminder(Integer courseId) {
        Course course = courseService.getCourseById(courseId);
        if (course == null) {
            logger.error("课程不存在，ID: {}", courseId);
            return false;
        }
        // 补齐班级名称（selectByPrimaryKey未关联classes表时cname为null）
        try {
            if (course.getCname() == null && course.getClassId() != null) {
                com.bskms.bean.Classes classes = classService.selectByPrimaryKey(course.getClassId());
                if (classes != null) {
                    course.setCname(classes.getName());
                }
            }
        } catch (Exception e) {
            logger.warn("获取班级名称失败，classId: {}", course.getClassId(), e);
        }
        
        return sendCourseReminder(course, 2);
    }
    
    @Override
    @Async
    public void sendManualCourseReminderAsync(Integer courseId) {
        try {
            sendManualCourseReminder(courseId);
        } catch (Exception e) {
            logger.error("异步发送课程提醒失败, 课程ID: {}", courseId, e);
        }
    }
    
    private boolean sendCourseReminder(Course course, Integer sendType) {
        try {
            // 获取班级所有家长
            List<User> parents = userService.getParentsByClassId(course.getClassId());
            
            // 发送邮件
            boolean emailResult = emailService.sendCourseReminderEmail(course, parents);
            
            // 记录发送结果
            CourseNotification notification = new CourseNotification();
            notification.setCourseId(course.getId());
            notification.setCourseName(course.getName());
            notification.setClassId(course.getClassId());
            notification.setClassName(course.getCname());
            notification.setSendTime(new Date());
            notification.setSendType(sendType);
            notification.setStatus(emailResult ? "SUCCESS" : "FAILED");
            notification.setCreateTime(new Date());
            
            if (!emailResult) {
                notification.setErrorMessage("邮件发送失败");
            }
            
            courseNotificationMapper.insert(notification);
            
            logger.info("课程提醒发送完成，课程: {}, 类型: {}, 结果: {}", 
                course.getName(), sendType == 1 ? "自动" : "手动", emailResult ? "成功" : "失败");
            
            return emailResult;
            
        } catch (Exception e) {
            logger.error("发送课程提醒异常，课程ID: {}, 异常: {}", course.getId(), e.getMessage(), e);
            
            // 记录失败
            CourseNotification notification = new CourseNotification();
            notification.setCourseId(course.getId());
            notification.setCourseName(course.getName());
            notification.setClassId(course.getClassId());
            notification.setClassName(course.getCname());
            notification.setSendTime(new Date());
            notification.setSendType(sendType);
            notification.setStatus("FAILED");
            notification.setErrorMessage(e.getMessage());
            notification.setCreateTime(new Date());
            
            try {
                courseNotificationMapper.insert(notification);
            } catch (Exception ex) {
                logger.error("记录通知失败", ex);
            }
            
            return false;
        }
    }

    @Override
    public boolean hasSentToday(Integer courseId) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String today = sdf.format(new Date());
            
            CourseNotification notification = courseNotificationMapper.selectByCourseIdAndDate(courseId, today);
            return notification != null;
        } catch (Exception e) {
            logger.error("检查发送记录异常，课程ID: {}", courseId, e);
            return false;
        }
    }

    @Override
    public List<CourseNotification> getCourseNotifications(Integer courseId) {
        return courseNotificationMapper.selectByCourseId(courseId);
    }
}
